/*
 * @Description:
 * @Author: Dxcr
 * @Date: 2024-09-05 09:25:38
 * @LastEditTime: 2025-03-12 15:01:30
 * @LastEditors: Dxcr
 */
import axios from "axios";
import router from "@/router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { saveAs } from 'file-saver';

const errorCode = {
  401: "认证失败，无法访问系统资源",
  403: "当前操作没有权限",
  404: "访问资源不存在",
  default: "系统未知错误，请反馈给管理员",
};

//处理code异常
const handleCode = (code, msg, data) => {
  // let reg = /^[\u4e00-\u9fa5]s/;
  // console.log('reg.test(data)', data, reg.test(data));
  switch (code) {
    case 401:
      ElMessage.error(msg || "登录失效");
      break;
    case 40001:
      ElMessage.error(msg || "登录失效");
      break;
    case 40003:
      router.push({ path: "/401" }).catch(() => {});
      break;
    case "-1":
      ElMessage.error(msg === "系统异常" ? data : msg);
      break;
    default:
      ElMessage.error(msg || `后端接口${code}异常`);
      break;
  }
};

//xios初始化
const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
});

//axios请求拦截器
instance.interceptors.request.use(
  (config) => {
    if (
      config.data &&
      config.headers["Content-Type"] ===
        "application/x-www-form-urlencoded;charset=UTF-8"
    )
      config.data = JSON.stringify(config.data);
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    if (getToken() && !isToken) {
      config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//axios响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.data?.msg_code === "GetSucc") return response.data;
    if (response.data?.msg === "获取成功！") return response.data;
    const { data, config } = response;
    //如果是文件流直接返回
    if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
      return data;
    }
    const { code, msg, data: _data } = data;
    // console.log(code)
    // if (code === 401) {
    //   if (!isRelogin.show) {
    //     isRelogin.show = true;
    //     ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
    //       isRelogin.show = false;
    //       useUserStore().logOut().then(() => {
    //         router.push({ path: "/login" });
    //       })
    //   }).catch(() => {
    //     isRelogin.show = false;
    //   });
    // }
    //   return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    // } else if (code === 500) {
    //   ElMessage({ message: msg, type: 'error' })
    //   return Promise.reject(new Error(msg))
    // } else if (code === 601) {
    //   ElMessage({ message: msg, type: 'warning' })
    //   return Promise.reject(new Error(msg))
    // } else if (code !== 200) {
    //   ElNotification.error({ title: msg })
    //   return Promise.reject('error')
    // } else {
    //   return  Promise.resolve(res.data)
    // }
    return _data;
  },
  (error) => {
    const { response, message } = error;
    if (error.response && error.response.data) {
      const { status, data } = response;
      handleCode(status, data.mesg || message);
      return Promise.reject(error);
    } else {
      let { message } = error;
      if (message === "Network Error") {
        message = "后端接口连接异常";
      }
      if (message.includes("timeout")) {
        message = "后端接口请求超时";
      }
      if (message.includes("Request failed with status code")) {
        const code = message.substr(message.length - 3);
        message = "后端接口" + code + "异常";
      }
      ElMessage.error(message || `后端接口未知异常`);
      return Promise.reject(error);
    }
  }
);

export default instance;

// 通用下载方法
export function download({
  url,
  method = "post",
  params,
  filename,
  config,
} = {}) {
  let downloadLoadingInstance = ElLoading.service({
    text: "正在下载数据，请稍候",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return instance(
    {
      url: url,
      method: method,
      params: params,
      // transformRequest: [(params) => { return tansParams(params) }],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: "blob",
      ...config,
    })
    .then(async (data) => {
      console.log(data)
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data]);
        saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
        ElMessage.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      ElMessage.error("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
}

export function preview(url, params, filename, type, config) {
  let urls = url + "?" + tansParams(params);
  return instance.post(
    urls,
    {},
    {
      //transformRequest: [(params) => { return tansParams(params) }],
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
      ...config,
    }
  );
}

function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 验证是否为blob格式
function blobValidate(data) {
  if (!data) {
    return false;
  }
  return data.type !== "application/json";
}
